package com.backend.api.security;

import com.common.model.Menu;
import com.backend.api.security.entity.SelfAdminEntity;
import com.common.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义权限注解验证
 */
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {

    private MenuService menuService;

    public UserPermissionEvaluator() {
        super();
    }

    @Autowired
    public UserPermissionEvaluator(MenuService menuService) {
        this.menuService = menuService;
    }

    /**
     * hasPermission鉴权方法
     * 这里仅仅判断PreAuthorize注解中的权限表达式
     * 实际中可以根据业务需求设计数据库通过targetUrl和permission做更复杂鉴权
     * 当然targetUrl不一定是URL可以是数据Id还可以是管理员标识等,这里根据需求自行设计
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {
        // 获取用户信息
        SelfAdminEntity selfAdminEntity = (SelfAdminEntity) authentication.getPrincipal();
        // 查询用户权限(这里可以将权限放入缓存中提升效率)
        Set<String> permissions = new HashSet<>();
        List<Menu> sysMenuEntityList = menuService.findByAdminId(selfAdminEntity.getAdminId());

        for (Menu sysMenuEntity : sysMenuEntityList) {
            permissions.add(sysMenuEntity.getPermission());
        }

        // 权限对比
        return permissions.contains(permission.toString());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}